<template>
	<div class="centerMap">
		<div class="map-container">
			<!-- 地图容器 -->
			<div ref="map" class="map-content"></div>
		</div>
	</div>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeUnmount, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { loadBMap } from './map.js';
import dataList from './data.js';
import 'echarts/extension/bmap/bmap';
import { debounce } from 'lodash-es';

// 设备状态枚举
enum DeviceStatus {
	INACTIVE = 1, // 未激活
	DISABLED = 2, // 禁用
	ONLINE = 3, // 在线
	OFFLINE = 4, // 离线
}

// 定位方式枚举
enum LocationWay {
	AUTO = 1, // 自动定位
	DEVICE = 2, // 设备定位
	CUSTOM = 3, // 自定义位置
}

// 设备接口定义
interface Device {
	deviceId: string;
	deviceName: string;
	longitude: number;
	latitude: number;
	serialNumber: string;
	status: DeviceStatus;
	isShadow: number;
	firmwareVersion: string;
	networkAddress: string;
	productName: string;
	activeTime: string | null;
	locationWay: LocationWay;
}

// 地图设备数据接口
interface MapDevice {
	name: string;
	value: [number, number];
	serialNumber: string;
	status: DeviceStatus;
	isShadow: number;
	firmwareVersion: string;
	networkAddress: string;
	productName: string;
	activeTime: string;
	deviceId: string;
	locationWay: LocationWay;
}

export default defineComponent({
	name: 'CenterMap',
	setup() {
		const router = useRouter();
		const map = ref<HTMLElement | null>(null); // 地图DOM引用
		const deviceList = ref<Device[]>([]); // 设备列表数据
		const deviceCount = ref(0); // 设备总数
		const timer = ref<NodeJS.Timeout | null>(null); // 轮询定时器
		const myChart = ref<echarts.ECharts | null>(null); // ECharts实例
		const queryParams = ref<Record<string, any>>({}); // 查询参数

		// 地图中心点和缩放级别配置
		const MAP_CENTER: [number, number] = [106, 37.5];
		const MAP_ZOOM = 5;
		const POLLING_INTERVAL = 120000; // 轮询间隔2分钟

		// 清理数据，主要是清除定时器
		const clearData = () => {
			if (timer.value) {
				clearInterval(timer.value);
				timer.value = null;
			}
		};

		// 轮询设备数据
		const startPolling = () => {
			if (timer.value) return;
			timer.value = setInterval(getAllDevice, POLLING_INTERVAL);
		};

		// 获取所有设备数据
		const getAllDevice = async () => {
			try {
				// 实际项目中这里应该是API调用
				// const response = await listAllDeviceShort(queryParams.value);
				// deviceList.value = response.rows;
				// deviceCount.value = response.total;

				// 使用模拟数据
				deviceList.value = dataList.data;
				deviceCount.value = dataList.total;

				loadMap();
				startPolling();
			} catch (error) {
				console.error('获取设备数据失败:', error);
			}
		};

		// 加载百度地图
		const loadMap = () => {
			loadBMap()
				.then(() => {
					console.log('百度地图加载完成'); // 确认这行执行了
					initMap();
				})
				.catch(() => {
					console.error('加载百度地图失败');
				});
		};

		// 转换设备数据为地图需要的格式
		const convertData = (data: Device[], status: DeviceStatus): MapDevice[] => {
			return data
				.filter((item) => item.longitude && item.latitude && item.status === status)
				.map((item) => ({
					name: item.deviceName,
					value: [item.longitude, item.latitude],
					serialNumber: item.serialNumber,
					status: item.status,
					isShadow: item.isShadow,
					firmwareVersion: item.firmwareVersion,
					networkAddress: item.networkAddress,
					productName: item.productName,
					activeTime: item.activeTime ?? '',
					deviceId: item.deviceId,
					locationWay: item.locationWay,
				}));
		};

		// 百度地图样式配置
		const MAP_STYLE = {
			mapStyle: {
				styleJson: [
					// 水体 - 保持深色但可见
					{ featureType: 'water', elementType: 'all', stylers: { color: '#4262D3' } },
					// 陆地 - 比背景稍亮
					{ featureType: 'land', elementType: 'geometry', stylers: { color: '#001421' } },
					// 边界 - 显示边界线
					{ featureType: 'boundary', elementType: 'all', stylers: { color: '#62CAD6', visibility: 'on' } },
					// 建筑物 - 显示但简化
					{ featureType: 'building', elementType: 'all', stylers: { color: '#3e3e3e', visibility: 'on' } },
					// 道路 - 显示主要道路
					{ featureType: 'highway', elementType: 'all', stylers: { visibility: 'simplified', color: '#4a4a4a' } },
					// 标签 - 确保文字可见
					{ featureType: 'label', elementType: 'labels.text.fill', stylers: { color: '#ffffff', visibility: 'on' } },
					{ featureType: 'label', elementType: 'labels.text.stroke', stylers: { color: '#000000', visibility: 'o' } },
					// 公园/绿地
					{ featureType: 'green', elementType: 'all', stylers: { color: '#1b1b1b' } },
					// 隐藏不必要元素
					{ featureType: 'railway', elementType: 'all', stylers: { visibility: 'off' } },
					{ featureType: 'subway', elementType: 'all', stylers: { visibility: 'off' } },
					{ featureType: 'arterial', elementType: 'labels.icon', stylers: { visibility: 'off' } },
				],
			},
		};

		// 格式化tooltip内容
		const formatTooltip = (data: MapDevice): string => {
			// 状态映射
			const statusMap = {
				[DeviceStatus.INACTIVE]: { text: '未激活', color: '#E6A23C' },
				[DeviceStatus.DISABLED]: { text: '禁用', color: '#F56C6C' },
				[DeviceStatus.ONLINE]: { text: '在线', color: '#67C23A' },
				[DeviceStatus.OFFLINE]: { text: '离线', color: '#909399' },
			};

			// 定位方式映射
			const locationWayMap = {
				[LocationWay.AUTO]: '自动定位',
				[LocationWay.DEVICE]: '设备定位',
				[LocationWay.CUSTOM]: '自定义位置',
			};

			return `
				<div style="padding:5px;line-height:28px;">
				设备名称： <span style='color:#FFF'>${data.name}</span><br />
				设备编号： ${data.serialNumber}<br />
				设备状态： <span style='color:${statusMap[data.status].color}'>${statusMap[data.status].text}</span><br />
				设备影子： <span style='color:${data.isShadow === 1 ? '#67C23A' : '#909399'}'>${data.isShadow === 1 ? '启用' : '未启用'}</span><br />
				产品名称： ${data.productName}<br />
				固件版本： Version ${data.firmwareVersion}<br />
				激活时间： ${data.activeTime}<br />
				定位方式： ${locationWayMap[data.locationWay] || '未知'}<br />
				所在地址： ${data.networkAddress}<br />
				</div>
			`;
		};

		// 获取series配置
		const getSeriesConfig = (data: Device[]) => [
			// 未激活设备
			{
				type: 'scatter',
				coordinateSystem: 'bmap',
				data: convertData(data, DeviceStatus.INACTIVE),
				symbolSize: 10,
				itemStyle: { color: '#e8fc05' },
			},
			// 禁用设备
			{
				type: 'scatter',
				coordinateSystem: 'bmap',
				data: convertData(data, DeviceStatus.DISABLED),
				symbolSize: 10,
				itemStyle: { color: '#fc3464' },
			},
			// 离线设备
			{
				type: 'scatter',
				coordinateSystem: 'bmap',
				data: convertData(data, DeviceStatus.OFFLINE),
				symbolSize: 10,
				itemStyle: { color: '#eee' },
			},
			// 在线设备（带涟漪特效）
			{
				type: 'effectScatter',
				coordinateSystem: 'bmap',
				data: convertData(data, DeviceStatus.ONLINE),
				symbolSize: 12,
				showEffectOn: 'render',
				rippleEffect: {
					brushType: 'stroke',
					scale: 5,
				},
				label: {
					formatter: '{b}',
					position: 'right',
					show: false,
				},
				itemStyle: {
					color: '#5de88e',
					shadowBlur: 100,
					shadowColor: '#333',
				},
				zlevel: 1,
			},
		];

		// 初始化地图
		const initMap = () => {
			if (!map.value) return;

			// 初始化ECharts实例
			myChart.value = echarts.init(map.value);

			// 点击事件处理
			myChart.value.on('click', (params: any) => {
				// if (params.data?.deviceId) {
				// 	router.push({
				// 		path: '/iot/device-edit',
				// 		query: {
				// 			t: Date.now().toString(),
				// 			deviceId: params.data.deviceId,
				// 		},
				// 	});
				// }
			});

			// ECharts配置项
			const option: echarts.EChartsOption = {
				backgroundColor: 'rgba(23,45,130,0.5)',
				tooltip: {
					trigger: 'item',
					backgroundColor: 'rgba(58,73,116,0.7)',
					textStyle: { color: 'rgba(65,235,246,1)' },
					formatter: (params: any) => formatTooltip(params.data),
				},
				bmap: {
					roam: true,
					zoom: MAP_ZOOM,
					center: MAP_CENTER,
					mapStyle: MAP_STYLE.mapStyle,
				},
				series: getSeriesConfig(deviceList.value),
			};

			// 设置配置项
			myChart.value.setOption(option, true);
		};

		// 处理窗口大小变化，防抖优化
		const handleResize = debounce(() => {
			myChart.value?.resize();
		}, 300);

		// 组件挂载时添加resize监听
		onMounted(() => {
			window.addEventListener('resize', handleResize);
			getAllDevice();
		});

		// 组件卸载前清理资源
		onBeforeUnmount(() => {
			window.removeEventListener('resize', handleResize);
			clearData();
			myChart.value?.dispose();
		});

		return {
			map,
			deviceList,
			deviceCount,
			queryParams,
		};
	},
});
</script>

<style lang="scss" scoped>
.centerMap {
	width: 100%;
	height: 100%;
	position: relative;

	.map-container {
		width: 100%;
		height: 100%;
		padding: 0.1rem;
		box-sizing: border-box;

		.map-content {
			width: 100%;
			height: 100%;
			background: #0e2e87; // 匹配地图陆地颜色

			/* 隐藏百度地图版权信息 */
			:deep(.BMap_cpyCtrl),
			:deep(.anchorBL) {
				display: none !important;
			}
		}
	}
}
</style>
